<template>
  <div class="detail-box">
    <div class="header">需求大厅-查看</div>
    <div class="detail">
      <div class="detail-item">
        <div class="detail-item-title">关联需求收集单</div>
        <div class="detail-item-order">
          <a-radio-group v-model:value="detailData.customerRequireFlag">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="2">否</a-radio>
          </a-radio-group>
          <div class="detail-item-order-select" v-if="detailData.customerRequireFlag === 1">
            <a-select style="width: 100%" placeholder="请选择" :filter-option="filterOption" allowClear show-search v-model:value="customerRequireId">
              <a-select-option v-for="item in list" :key="item.id" :value="item.id" :data-name="item.requireName">{{ item.requireName }}</a-select-option>
            </a-select>
          </div>
        </div>
      </div>
      <div class="detail-item">
        <div class="detail-item-title">需求信息</div>
        <div class="detail-item-requirement">
          <div class="detail-item-req-ite detail-item-req-name">
            <text class="lable">名称</text>
            <text class="code">{{ detailData.requireName }}</text>
          </div>
          <div class="detail-item-req-ite detail-item-req-name">
            <text class="lable">详细描述</text>
            <text class="code">{{ detailData.requireDesc ?? '--' }}</text>
          </div>
          <div class="detail-item-req-ite">
            <text class="lable">周期</text>
            <text class="code">{{ detailData.requireBeginTime }} 至 {{ detailData.requireEndTime }}</text>
          </div>
          <div class="detail-item-req-ite">
            <text class="lable">数量</text>
            <text class="code">{{ detailData.requireAmount }}</text>
          </div>
          <div class="detail-item-req-ite">
            <text class="lable">预算 </text>
            <text class="code">{{ detailData.requireBudget }}</text>
          </div>
          <div class="detail-item-req-ite">
            <text class="lable">logo</text>
            <img alt="" class="icon" v-if="detailData.requireLogo" :src="detailData.requireLogo" />
            <text class="code" v-else>无</text>
          </div>
          <div class="detail-item-req-ite">
            <text class="lable">标签</text>
            <text class="code">{{ detailData.labels }}</text>
          </div>
          <div class="detail-item-req-ite">
            <text class="lable">来源</text>
            <text class="code">{{ detailData.requireSource }}</text>
          </div>
        </div>
      </div>
      <div class="detail-item">
        <div class="detail-item-title">具体要求</div>
        <div class="detail-item-requirement">
          <div class="detail-item-req-ite">
            <text class="lable">类型</text>
            <text class="code">{{ dataTypeObj[detailData.dataType] }}</text>
          </div>
          <div class="detail-item-req-ite">
            <text class="lable">大小</text>
            <text class="code">{{ dataLimitObj[detailData.dataLimit] }}</text>
          </div>
          <div class="detail-item-req-ite detail-item-req-name">
            <text class="lable">技术要求</text>
            <text class="code">{{ detailData.techRequire }}</text>
          </div>
          <div class="detail-item-req-ite detail-item-req-name">
            <text class="lable">样例</text>
            <template v-if="detailData.sampleTemp && detailData.sampleTemp.length">
              <a class="title-btn" @click="batchDownload">下载</a>
            </template>
            <text class="code" v-else>无</text>
          </div>
          <div class="detail-item-req-ite detail-item-req-name" v-if="detailData.sampleTemp && detailData.sampleTemp.length">
            <div class="sample-temp">
              <div v-for="item in detailData.sampleTemp" :key="item.fileId">
                <a-button type="link" size="small" @click="unstructuredPreviewFile(item.fileId)" :loading="previewLoading && fileId === item.fileId">{{ item.fileName }}</a-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="detail-item">
        <div class="detail-item-title">参与需求管理</div>
        <div class="detail-item-requirement">
          <div class="detail-item-req-ite detail-item-req-name">
            <text class="lable">需求总数</text>
            <text class="code">{{ detailData.requireAmount }}个</text>
          </div>
          <div class="detail-item-req-ite detail-item-req-name">
            <text class="lable">已参与</text>
            <text class="code">{{ detailData.collectedAmount }}个</text>
            <a class="btn" @click="goToFormList(detailData.requireName)">查看详情</a>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <a-button type="primary" @click="onEdit">编辑</a-button>
      <a-button class="back" @click="pageBack()">返回</a-button>
    </div>
    <!-- 预览非结构化数据 -->
    <a-modal v-model:visible="previewVisible" title="预览" :footer="null" @cancel="handleCancel">
      <img alt="" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import axios from 'axios'
  import { onMounted, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { getCustomerRequireData, getRequireDetail, saveRequire } from '/@/api/exchange/requirement'
  import { getToken } from '/@/storage'

  import { dataLimitObj, dataTypeObj } from './data'

  const token = getToken() || ''
  const router = useRouter()
  const route = useRoute()
  const { id } = route.query
  const platformCode = import.meta.env.VITE_GLOB_PLATFORMCODE
  const list = ref<RequirementTypes.IResponse[]>([])
  const customerRequireId = ref<string>()
  const detailData = ref<RequirementTypes.DetailIResponse>({
    id: '',
    customerRequireFlag: null,
    requireName: '',
    requireDesc: '',
    requireBeginTime: '',
    requireEndTime: '',
    requireBudget: null,
    requireAmount: null,
    collectedAmount: null,
    assRequire: {},
    techRequire: '',
    sampleTemp: [],
    qualificationsDesc: '',
    requireSource: '',
    labels: '',
    coinType: null,
    dataType: null,
    dataLimit: null,
    qualificationsFlag: null,
    dictResults: {},
  })
  // 预览非结构化数据
  const fileId = ref<string>()
  const previewLoading = ref(false)
  const previewVisible = ref(false)
  const previewImage = ref<string>()

  const filterOption = (input: string, option: any) => {
    return option['data-name'] && option['data-name'].toLowerCase().indexOf(input.toLowerCase()) >= 0
  }

  // 非结构化数据预览
  const unstructuredPreviewFile = async (id: string) => {
    fileId.value = id
    const fileUrl = `${import.meta.env.VITE_BASE_API_PATH}/zeus/standard/dc-file/unstructuredPreviewDownload`
    const formData = new FormData()
    formData.append('id', id)
    formData.append('platformCode', platformCode)
    previewLoading.value = true
    try {
      // 发送 POST 请求
      const response = await axios.post(fileUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: token,
        },
        responseType: 'blob', // 指定响应类型为二进制数据
      })
      // 处理响应
      if (response.status === 200) {
        const blob = new Blob([response.data], { type: response.headers['content-type'] })
        const url = window.URL.createObjectURL(blob)
        if (url) {
          previewImage.value = url
          previewVisible.value = true
        } else {
          message.error('预览失败，请重试')
        }
        previewLoading.value = false
      } else {
        throw new Error('预览失败')
        previewLoading.value = false
      }
    } catch (error) {
      previewLoading.value = false
      console.error('预览出错:', error)
      message.error('预览失败，请重试')
    }
  }
  // 关闭预览
  const handleCancel = () => {
    previewVisible.value = false
    previewImage.value = ''
  }

  // 批量下载
  const batchDownload = async () => {
    const fileList = [...detailData.value.sampleTemp]
    const fileIds = fileList.map((item) => item.fileId)
    const fileUrl = `${import.meta.env.VITE_BASE_API_PATH}/zeus/standard/dc-file/batchFileDownload`
    const formData = new FormData()
    formData.append('ids', fileIds.join(','))
    formData.append('platformCode', platformCode)
    try {
      // 发送 POST 请求
      const response = await axios.post(fileUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: token,
        },
        responseType: 'blob', // 指定响应类型为二进制数据
      })

      // 处理响应
      if (response.status === 200) {
        // 创建一个临时链接
        const url = window.URL.createObjectURL(new Blob([response.data]))
        // 创建一个隐藏的 <a> 标签
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'files.zip') // 设置下载文件的名称
        document.body.appendChild(link)
        link.click() // 触发下载
        document.body.removeChild(link) // 移除 <a> 标签
        window.URL.revokeObjectURL(url) // 释放临时链接
      } else {
        throw new Error('下载失败')
      }
    } catch (error) {
      console.error('下载出错:', error)
      message.error('下载失败，请重试')
    }
  }

  /**回退页面*/
  const pageBack = () => {
    router.back()
  }

  const onEdit = async () => {
    /**编辑需求详情 */
    router.push({
      path: '/requirement/create',
      query: { id: detailData.value.id },
    })
  }

  /**获取详情*/
  const getDetail = async () => {
    const params = { platformRequireId: id }
    const { responseData } = await getRequireDetail(params)
    if (responseData) {
      detailData.value = responseData
      const labelList = responseData.labels ? JSON.parse(responseData.labels) : []
      const labelString = labelList.join('、')
      detailData.value.labels = labelString
      if (responseData.customerRequireFlag === 1) {
        customerRequireId.value = responseData.assRequire && responseData.assRequire.id ? Number(responseData.assRequire.id) : ''
      } else {
        customerRequireId.value = undefined
      }
    }
  }

  /**获取需求单列表*/
  const getCustomerRequireList = async () => {
    const { responseData } = await getCustomerRequireData()
    list.value = responseData || []
  }

  const goToFormList = (requireName: string) => {
    router.push({
      path: '/requirement/attend-list',
      query: { requireName },
    })
  }

  onMounted(() => {
    if (id) getDetail()
    getCustomerRequireList()
  })
</script>
<style lang="less" scoped>
  .detail-box {
    width: 100%;
    padding: 0 24px 30px;
    background: #fff;
    border-radius: 2px;

    .header {
      width: 100%;
      height: 64px;
      border-bottom: 1px solid #f2f3f5;
      font-size: 16px;
      font-weight: bold;
      color: #000;
      line-height: 64px;
    }

    .detail {
      width: 100%;
      margin-top: 20px;
      font-size: 16px;

      .detail-item {
        width: 100%;
        margin-bottom: 40px;

        .detail-item-title {
          color: #000;
        }

        &:first-child {
          display: flex;
          align-items: flex-start;
        }

        .detail-item-order {
          margin-left: 20px;

          .detail-item-order-select {
            width: 200px;
            margin-top: 20px;
          }
        }

        .detail-item-requirement {
          width: 100%;
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          padding: 0 20px;
          box-sizing: border-box;

          .detail-item-req-ite {
            margin-top: 20px;
            width: 30%;
            font-size: 14px;
            display: flex;

            .lable {
              color: #666;
              padding-right: 10px;
            }

            .code {
              color: #000;
            }

            .icon {
              width: 80px;
              height: 80px;
              background: #f2f3f5;
              vertical-align: top;
            }

            .btn {
              padding-left: 30px;
            }

            .sample-temp {
              margin-left: 10px;
              color: #000;
            }
          }

          .detail-item-req-name {
            width: 100%;
          }
        }
      }
    }

    .footer {
      width: 100%;
      border-top: 1px solid #f2f3f5;
      padding-top: 20px;

      .back {
        margin-left: 20px;
      }
    }
  }
</style>
